<template>
  <div class="desktop-wallet-connect-qrcode">
    <div
      v-if="qrcodeLoading"
      style="
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        color: #d9fc01;
      "
      :style="{ width: '350px', height: '350px' }"
    >
      <img
        :src="wallet.icon ?? wallet.iconUrl"
        style="position: absolute; border-radius: 8px"
        :style="{ width: '72px', height: '72px', filter: 'blur(8px)' }"
      />
      <Spinner :width="36" :height="36" />
    </div>
    <template v-else>
      <img
        :src="wallet.icon ?? wallet.iconUrl"
        style="position: absolute; border-radius: 8px"
        :style="{ width: '72px', height: '72px' }"
      />
      <Qrcode
        :uri="qrcodeUri"
        ecl="M"
        :logo-margin="10"
        :logo-size="72"
        :size="350"
      />
    </template>
  </div>
</template>
<script setup lang="ts">
import { type WalletConnector } from '../../wallets/useWalletConnectors'
import Spinner from '../Icons/Spinner.vue'
import Qrcode from './Qrcode.vue'
import { ref, watch } from 'vue'

const props = withDefaults(defineProps<{ wallet: WalletConnector }>(), {})
const qrcodeUri = ref()
const qrcodeLoading = ref(false)

const getWalletQRCodeUri = (wallet: WalletConnector) => {
  const { connect, getQrCodeUri } = wallet

  const onQRCodeUri = async () => {
    qrcodeLoading.value = true
    const qRCodeUri = await getQrCodeUri?.()

    if (!qRCodeUri) return

    qrcodeUri.value = qRCodeUri

    qrcodeLoading.value = false
  }

  onQRCodeUri()

  connect?.()
}

const createQRcode = () => {
  if (
    props.wallet &&
    props.wallet.getQrCodeUri &&
    props.wallet.isWalletKitConnector &&
    props.wallet.ready &&
    !props.wallet.installed
  ) {
    getWalletQRCodeUri(props.wallet)
  }
}

watch(
  () => props.wallet?.id,
  () => {
    createQRcode()
  },
  {
    immediate: true,
  },
)
</script>

<style lang="scss" scoped>
.desktop-wallet-connect-qrcode {
  background: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  position: relative;
}
</style>
